package com.hongxun.design.activitys;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.webkit.WebView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hongxun.design.MyApp;
import com.hongxun.design.R;
import com.hongxun.design.interfaces.HeadSecond;
import com.hongxun.design.listeners.ListenerSet;
import com.hongxun.design.mytools.IconSourse;
import com.hongxun.design.mytools.MString;
import com.hongxun.design.mytools.MyLog;
import com.hongxun.design.mytools.SetTypeface;
import com.hongxun.design.mytools.ToastShow;
import com.hongxun.design.ui.headandbottonpanel.HeadSecondControlPanel;
import com.hongxun.design.utils.DataUtil;
import com.hongxun.design.utils.PopwindowUtil;
import com.hongxun.design.utils.fastjson.FastJsonUtil;
import com.hongxun.design.utils.httputil.HttpStringUtil;
import com.umeng.socialize.UMShareAPI;

/**
 * Created by zerdoor_pc on 2016/6/20.
 * 百科详情
 */
public class EncyclopediasActivity extends BaseActivity implements HeadSecond {
    String encyclopedia_id, CONTENT = "", title = "", favorite_id = "", id = "";
    String type = "";
    WebView webView;
    private Handler encyclopediaContentHandler, experienceContentHandler, collectHandler, sysArticleContentHandler;
    HeadSecondControlPanel encyclopedias_layout;
    int check;
    int uncheck;
    String check_icon = (String) IconSourse.collect;
    String uncheck_icon = (String) IconSourse.Favorite;
    boolean iscollect = false;
    String tag = "EncyclopediasActivity_";
    String tagCarouse = "EncyclopediasActivity_Carouse";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_encyclopedias);
        check = getResources().getColor(R.color.login_yellow);
        uncheck = getResources().getColor(R.color.bar_right);
        findBar();
        findView();
    }

    @SuppressLint("NewApi")
    private void getTitleId() {
        Bundle bundle = getIntent().getExtras();

        type = bundle.getString(MString.TYPE);
        switch (type) {
            case MString.Carouse:
                id = bundle.getString(MString.CODE);
                title = bundle.getString(MString.TITLE);
                break;
            case MString.Encyclopedias:
                encyclopedia_id = bundle.getString(MString.CODE);
                title = bundle.getString(MString.TITLE);
                favorite_id = bundle.getString(MString.SENDCODE, "");
                if (favorite_id.length() > 0) {
                    iscollect = true;
                }
                break;
            case MString.EXPERIENCE:
                encyclopedia_id = bundle.getString(MString.CODE);
                title = bundle.getString(MString.TITLE);

                break;

            case MString.MYNEW:
                encyclopedia_id = bundle.getString(MString.CODE);
                title = bundle.getString(MString.TITLE);
                CONTENT = bundle.getString(MString.CONTENT);
                break;

            case MString.MYSYSTEM:
                encyclopedia_id = bundle.getString(MString.CODE);
                id = bundle.getString(MString.id);
                title = bundle.getString(MString.TITLE);
                CONTENT = bundle.getString(MString.CONTENT);
                break;

            case MString.AUTHORIZATION:
                encyclopedia_id = bundle.getString(MString.CODE);
                title = bundle.getString(MString.TITLE);
                CONTENT = bundle.getString(MString.CONTENT);
                break;
        }

    }


    @Override
    public void findBar() {
        getTitleId();
        encyclopedias_layout = (HeadSecondControlPanel) findViewById(R.id.encyclopedias_layout);
        switch (type) {
            case MString.Carouse:
                encyclopedias_layout.initHeadPanel(DataUtil.getsecondbean("", View.INVISIBLE, R.color.bar_right, ListenerSet.back, title, R.color.title, View.VISIBLE, IconSourse.BACK + "", View.VISIBLE));
                break;
            case MString.EXPERIENCE:
                encyclopedias_layout.initHeadPanel(DataUtil.getsecondbean("", View.INVISIBLE, R.color.bar_right, ListenerSet.back, title, R.color.title, View.VISIBLE, IconSourse.BACK + "", View.VISIBLE));
                break;
            case MString.MYNEW:
                encyclopedias_layout.initHeadPanel(DataUtil.getsecondbean("", View.INVISIBLE, R.color.bar_right, ListenerSet.back, title, R.color.title, View.VISIBLE, IconSourse.BACK + "", View.VISIBLE));
                break;
            case MString.MYSYSTEM:
                encyclopedias_layout.initHeadPanel(DataUtil.getsecondbean("", View.INVISIBLE, R.color.bar_right, ListenerSet.back, title, R.color.title, View.VISIBLE, IconSourse.BACK + "", View.VISIBLE));
                break;
            case MString.AUTHORIZATION:
                encyclopedias_layout.initHeadPanel(DataUtil.getsecondbean("", View.INVISIBLE, R.color.bar_right, ListenerSet.back, title, R.color.title, View.VISIBLE, IconSourse.BACK + "", View.VISIBLE));
                break;
            case MString.Encyclopedias:
                encyclopedias_layout.initHeadPanel(DataUtil.getsecondbean(IconSourse.Favorite + "", View.VISIBLE, R.color.bar_right, ListenerSet.back, title, R.color.title, View.VISIBLE, IconSourse.BACK + "", View.VISIBLE));
                SetTypeface.set(encyclopedias_layout.share, IconSourse.share);
                if (iscollect) {
                    colected();
                } else {
                    unColected();
                }
                encyclopedias_layout.setClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (iscollect) {
                            delCollect();
                        } else {
                            addCollect();
                        }


                    }
                });
                encyclopedias_layout.share.setVisibility(View.VISIBLE);
                encyclopedias_layout.share.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        //分享
                        PopwindowUtil.sharePop(mActivity, view,share_title,share_thumb,share_url+encyclopedia_id,share_intro);
                        //MyApp.SHARE.shareCustom(mActivity, SHARE_MEDIA.QQ, "ces", "www.baidu,com", "测试测试", "http://img5.imgtn.bdimg.com/it/u=1889250223,3195298994&fm=21&gp=0.jpg");
                    }
                });
                break;
        }


    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult( requestCode, resultCode, data);
    }
    @Override
    protected void onResume() {
        super.onResume();
        MyApp.activity = this;
        mActivity = this;
        baseActivity = this;
    }

    @Override
    protected void findView() {
        super.findView();
        webView = (WebView) findViewById(R.id.encyclopedias_web);

        initialization();
    }

    @Override
    protected void initialization() {
        super.initialization();
        String s;
        switch (type) {
            case MString.Carouse:
                addSysArticleContentHandler();
                // s = MyApp.File.getJson(tagCarouse + id);
//                if (s != null && s.length() > 0) {
//                    sysArticleContentHandler.sendMessage(MyMessage.getMessage(HttpStringUtil.SUCCESSED, s));
//                }
                getSysArticleContent();
                break;
            case MString.MYSYSTEM:
                addSysArticleContentHandler();

                getSysArticleContent();
                break;
            case MString.Encyclopedias:
                addEncyclopediaContentHandler();
                addCollectHandler();
                //s = MyApp.File.getJson(tag + encyclopedia_id);
                // if (s != null && s.length() > 0) {
                // encyclopediaContentHandler.sendMessage(MyMessage.getMessage(HttpStringUtil.SUCCESSED, s));
                //}
                getEncyclopediaContent();
                break;
            case MString.EXPERIENCE:
                addExperienceContentHandler();
                GetExperienceContent();
                break;
            case MString.MYNEW:
                webView.loadDataWithBaseURL(null, CONTENT, "text/html", "UTF-8", null);
                break;

            case MString.AUTHORIZATION:
                webView.loadDataWithBaseURL(null, CONTENT, "text/html", "UTF-8", null);
                break;
        }

    }


    /**
     * 获取系统文章内容*
     */
    private void getSysArticleContent() {
        MyApp.HTTP.getSysArticleContent(sysArticleContentHandler, HttpStringUtil.SUCCESSED, id);
    }

    /**
     * 加载系统文章接收器*
     */
    private void addSysArticleContentHandler() {
        sysArticleContentHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case HttpStringUtil.SUCCESSED:
                        String s = FastJsonUtil.JsonToCheck_String((String) msg.obj);
                        if (FastJsonUtil.JsonToCheck((String) msg.obj)) {
                            String words = "";
                            try {
                                //MyApp.File.SaveFileData(tagCarouse + id, (String) msg.obj);
                                JSONObject articleContent = (JSONObject) JSON.parseObject((String) msg.obj).get("articleContent");
                                words = articleContent.getString("contents");
                                //    String filsh = replaceString(words, "<img src=", "<img src=" + HttpStringUtil.HeadSpeech + "/");
                                String filsh = words.replace("<img src=\"", "<img src=\"" + HttpStringUtil.HeadSpeech + "/");

                                String head = "<html><head><meta name=\"viewport\" content=\"width=320.1,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no,minimal-ui\"><style type=\"text/css\">img{max-width:100%;}</style></head><body>";
                                String end = "</body></html>";
                                MyLog.L(MString.SUCCESSED + " filsh=" + head + filsh + end);
                                webView.loadDataWithBaseURL(null, head + filsh + end, "text/html", "UTF-8", null);
                            } catch (Exception e) {
                            }
                        } else {
                            ToastShow.showShort(EncyclopediasActivity.this, s);
                        }
                        break;
                    case HttpStringUtil.ERROR:
                        break;
                }
            }
        };
    }

    /**
     * 获取经验内容*
     */
    private void GetExperienceContent() {
        MyApp.HTTP.GetExperienceContent(experienceContentHandler, HttpStringUtil.SUCCESSED, encyclopedia_id);
    }


    /**
     * 获取百科内容*
     */
    private void getEncyclopediaContent() {
        MyApp.HTTP.getEncyclopediaContent(encyclopediaContentHandler, HttpStringUtil.SUCCESSED, encyclopedia_id);
    }

    /**
     * 收藏百科*
     */
    private void addCollect() {
        MyApp.HTTP.addCollect(collectHandler, HttpStringUtil.SUCCESSED, encyclopedia_id);
    }

    /**
     * 删除收藏百科*
     */
    private void delCollect() {
        MyApp.HTTP.delCollect(collectHandler, HttpStringUtil.SUCCESSED, favorite_id);
    }


    /**
     * 获取百科内容handler*
     */
    public String share_title="",share_thumb="",share_url=HttpStringUtil.HeadSpeech+ "/shareController.do?view&id=",share_intro="";
    private void addEncyclopediaContentHandler() {
        encyclopediaContentHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case HttpStringUtil.SUCCESSED:
                        String s = FastJsonUtil.JsonToCheck_String((String) msg.obj);
                        if (FastJsonUtil.JsonToCheck((String) msg.obj)) {
                            String words = "";
                            try {
                                // MyApp.File.SaveFileData(tag + encyclopedia_id, (String) msg.obj);
                                JSONObject articleContent = (JSONObject) JSON.parseObject((String) msg.obj).get("articleContent");
                                share_title= articleContent.getString("title");
                                share_thumb=articleContent.getString("article_thumb");
                                share_intro=articleContent.getString("intro");
                                articleContent.getIntValue("is_favorite");
                                if (articleContent.getIntValue("is_favorite") == 1) {
                                    colected();
                                } else if (articleContent.getIntValue("is_favorite") == 0) {
                                    unColected();
                                }
                                words = articleContent.getString("content");
                                //    String filsh = replaceString(words, "<img src=", "<img src=" + HttpStringUtil.HeadSpeech + "/");
                                String filsh = words.replace("<img src=\"", "<img src=\"" + HttpStringUtil.HeadSpeech + "/");
                                String head = "<html><head><meta name=\"viewport\" content=\"width=320.1,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no,minimal-ui\"><style type=\"text/css\">img{max-width:100%;}</style></head><body><p>"+share_intro+"</p>";
                                String end = "</body></html>";
                                MyLog.L(MString.SUCCESSED + " filsh=" +head+ filsh+end);

                                webView.loadDataWithBaseURL(null, head+ filsh+end, "text/html", "UTF-8", null);
                                favorite_id = articleContent.getString("favorite_id");
                            } catch (Exception e) {
                            }
                        } else {
                            ToastShow.showShort(EncyclopediasActivity.this, s);
                        }
                        break;
                    case HttpStringUtil.ERROR:
                        break;
                }
            }
        };
    }

    /**
     * 获取经验内容handler*
     */
    private void addExperienceContentHandler() {
        experienceContentHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case HttpStringUtil.SUCCESSED:
                        String s = FastJsonUtil.JsonToCheck_String((String) msg.obj);
                        if (FastJsonUtil.JsonToCheck((String) msg.obj)) {
                            String words = "";
                            try {
                                // MyApp.File.SaveFileData(tag + encyclopedia_id, (String) msg.obj);
                                JSONObject articleContent = (JSONObject) JSON.parseObject((String) msg.obj).get("articleContent");

                                words = articleContent.getString("content");
                                //    String filsh = replaceString(words, "<img src=", "<img src=" + HttpStringUtil.HeadSpeech + "/");
                                String filsh = words.replace("<img src=\"", "<img src=\"" + HttpStringUtil.HeadSpeech + "/");
                                String head = "<html><head><meta name=\"viewport\" content=\"width=320.1,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no,minimal-ui\"><style type=\"text/css\">img{max-width:100%;}</style></head><body>";
                                String end = "</body></html>";
                                MyLog.L(MString.SUCCESSED + " filsh=" +head+ filsh+end);
                                webView.loadDataWithBaseURL(null, head+ filsh+end, "text/html", "UTF-8", null);

                            } catch (Exception e) {
                            }
                        } else {
                            ToastShow.showShort(EncyclopediasActivity.this, s);
                        }
                        break;
                    case HttpStringUtil.ERROR:
                        break;
                }
            }
        };
    }

    /**
     * 收藏百科handler*
     */

    private void addCollectHandler() {
        collectHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case HttpStringUtil.SUCCESSED:
                        String s = FastJsonUtil.JsonToCheck_String((String) msg.obj);
                        if (FastJsonUtil.JsonToCheck((String) msg.obj)) {
                            try {
                                String old = MyApp.File.getJson(tag + encyclopedia_id);
                                JSONObject articleContent = null;
                                if (old.length() > 0) {
                                    articleContent = (JSONObject) JSON.parseObject(old).get("articleContent");
                                }
                                if (iscollect) {
                                    unColected();
                                    ToastShow.showShort(EncyclopediasActivity.this, "删除成功！");
                                    if (articleContent != null)
                                        articleContent.put("is_favorite", 0);
                                } else {
                                    colected();
                                    ToastShow.showShort(EncyclopediasActivity.this, "收藏成功！");
                                    favorite_id = JSON.parseObject((String) msg.obj).getString("favorite_id");
                                    if (articleContent != null)
                                        articleContent.put("is_favorite", 1);
                                }
                                if (articleContent != null)
                                    MyApp.File.SaveFileData(tag + encyclopedia_id, JSON.toJSONString(articleContent));
                            } catch (Exception e) {
                            }
                        } else {
                            ToastShow.showShort(EncyclopediasActivity.this, s);
                        }

                        break;
                    case HttpStringUtil.ERROR:
                        ToastShow.showShort(EncyclopediasActivity.this, (String) msg.obj);
                        break;
                }
            }
        };
    }

    private void colected() {
        iscollect = true;
        encyclopedias_layout.mRightTitle.setTextColor(check);
        SetTypeface.set(encyclopedias_layout.mRightTitle, check_icon);
    }

    private void unColected() {
        encyclopedias_layout.mRightTitle.setTextColor(uncheck);
        SetTypeface.set(encyclopedias_layout.mRightTitle, uncheck_icon);
        iscollect = false;
    }

}
